<template>
  <nav-bar />
  <view class="lost-and-found-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="nav-back" @click="onBack">&#8592;</text>
      <text class="nav-title">失物招领</text>
      <text class="nav-add" @click="onAdd">+</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrap">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索物品名称" 
          @input="onSearch"
        />
      </view>
      <picker 
        class="status-picker" 
        :range="statusList" 
        range-key="name" 
        @change="onStatusFilterChange"
      >
        <view class="picker-value">{{ selectedFilterStatus ? selectedFilterStatus.name : '全部状态' }}</view>
      </picker>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      class="list-container" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="waterfall-container">
        <view class="waterfall-column">
          <view 
            class="list-item" 
            v-for="(item, index) in leftList" 
            :key="item.lost_and_found_id"
            @click="onItemClick(item)"
          >
            <view class="item-images" v-if="item.images && item.images.length > 0">
              <image 
                class="item-image" 
                :src="typeof item.images[0] === 'object' ? (IntranetConfig.domain + item.images[0].image) : item.images[0].image" 
                mode="widthFix"
                @load="onImageLoad($event, index, 'left')"
                @click.stop="openPreview(item.images, index)"
              />
            </view>
            <view class="item-content">
              <view class="item-header">
                <text class="item-name">{{ item.lost_and_found_name }}</text>
                <text class="item-status" :class="'status-' + item.lost_and_found_status">
                  {{ getStatusName(item.lost_and_found_status) }}
                </text>
              </view>
              <view class="item-info">
                <text class="item-location">{{ item.lost_and_found_location }}</text>
                <text class="item-time">{{ formatTime(item.create_time) }}</text>
              </view>
              <view class="item-description" v-if="item.lost_and_found_description">
                {{ item.lost_and_found_description }}
              </view>
              <view class="item-creator" v-if="item.user">
                <image class="creator-avatar" :src="IntranetConfig.domain + item.user.avatar" mode="aspectFill" />
                <text class="creator-name">{{ item.user.username }}</text>
              </view>
            </view>
            <view class="item-actions">
              <text class="action-btn edit" @click.stop="onEdit(item)">编辑</text>
              <text class="action-btn delete" @click.stop="onDelete(item)">删除</text>
            </view>
          </view>
        </view>
        <view class="waterfall-column">
          <view 
            class="list-item" 
            v-for="(item, index) in rightList" 
            :key="item.lost_and_found_id"
            @click="onItemClick(item)"
          >
            <view class="item-images" v-if="item.images && item.images.length > 0">
              <image 
                class="item-image" 
                :src="typeof item.images[0] === 'object' ? (IntranetConfig.domain + item.images[0].image) : item.images[0].image" 
                mode="widthFix"
                @load="onImageLoad($event, index, 'right')"
                @click.stop="openPreview(item.images, index)"
              />
            </view>
            <view class="item-content">
              <view class="item-header">
                <text class="item-name">{{ item.lost_and_found_name }}</text>
                <text class="item-status" :class="'status-' + item.lost_and_found_status">
                  {{ getStatusName(item.lost_and_found_status) }}
                </text>
              </view>
              <view class="item-info">
                <text class="item-location">{{ item.lost_and_found_location }}</text>
                <text class="item-time">{{ formatTime(item.create_time) }}</text>
              </view>
              <view class="item-description" v-if="item.lost_and_found_description">
                {{ item.lost_and_found_description }}
              </view>
              <view class="item-creator" v-if="item.user">
                <image class="creator-avatar" :src="IntranetConfig.domain + item.user.avatar" mode="aspectFill" />
                <text class="creator-name">{{ item.user.username }}</text>
              </view>
            </view>
            <view class="item-actions">
              <text class="action-btn edit" @click.stop="onEdit(item)">编辑</text>
              <text class="action-btn delete" @click.stop="onDelete(item)">删除</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore">
        <text class="loading-text">加载中...</text>
      </view>
      <view class="no-more" v-else>
        <text class="no-more-text">没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="footer-bar">
      <button class="add-btn" @click="onAdd">发布失物招领</button>
    </view>

    <!-- 新增/编辑弹窗 -->
    <uni-popup ref="formPopup" type="center">
      <view class="form-popup">
        <view class="popup-header">
          <text class="popup-title">{{ isEdit ? '编辑失物招领' : '发布失物招领' }}</text>
          <text class="popup-close" @click="closeFormPopup">×</text>
        </view>
        <scroll-view class="popup-content" scroll-y>
    <!-- 多图横向滚动 -->
    <scroll-view 
      class="lost-img-list-horizontal" 
      scroll-x 
      :scroll-with-animation="true"
      :enhanced="true"
      :show-scrollbar="false"
      :bounces="true"
    >
      <view class="img-list-row">
        <view class="img-box-horizontal" v-for="(img, index) in form.images" :key="index">
                <image class="lost-img-horizontal" :src="typeof img === 'object' ? (IntranetConfig.domain + img.image) : img" mode="aspectFill" />
                <view class="img-delete-horizontal" @click.stop="onImgDelete(index)">×</view>
        </view>
        <!-- 上传按钮 -->
        <view class="img-box-horizontal add-img-horizontal" @click="onAddImg">
          <text class="add-icon-horizontal">+</text>
        </view>
      </view>
    </scroll-view>

    <!-- 表单区域 -->
    <view class="form-section">
            <view class="form-grid">
              <view class="form-group">
                <text class="form-label required">物品名称</text>
                <input class="form-input" v-model="form.lost_and_found_name" placeholder="请输入物品名称" maxlength="100" />
      </view>

              <view class="form-group">
                <text class="form-label required">物品状态</text>
                <picker class="form-picker" :range="statusList" range-key="name" @change="onStatusChange">
          <view class="picker-value">{{ selectedStatus ? selectedStatus.name : '请选择' }}</view>
        </picker>
      </view>

              <view class="form-group" v-if="form.lost_and_found_status === 2">
                <text class="form-label">认领者姓名</text>
                <input class="form-input" v-model="form.lost_and_found_claimer_name" placeholder="请输入认领者姓名" maxlength="100" />
      </view>

              <view class="form-group" v-if="form.lost_and_found_status === 2">
                <text class="form-label">认领者联系方式</text>
                <input class="form-input" v-model="form.lost_and_found_claimer_contact" placeholder="请输入联系方式" maxlength="100" />
      </view>

              <view class="form-group">
                <text class="form-label required">物品位置</text>
                <input class="form-input" v-model="form.lost_and_found_location" placeholder="请输入物品位置" maxlength="100" />
              </view>
      </view>

            <view class="description-group" @click="showDescriptionPopup">
              <text class="form-label">物品描述</text>
              <view class="description-preview">
                <text class="description-text">{{ form.lost_and_found_description || '请输入物品描述' }}</text>
          <text class="arrow">></text>
        </view>
      </view>
    </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="cancel-btn" @click="closeFormPopup">取消</button>
          <button class="confirm-btn" @click="onSave">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 描述弹窗 -->
    <uni-popup ref="descriptionPopup" type="center">
      <view class="description-popup">
        <view class="popup-header">
          <text class="popup-title">物品描述</text>
          <text class="popup-close" @click="closeDescriptionPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="history-section" v-if="descriptionHistory.length > 0">
            <view class="history-title">历史记录</view>
            <scroll-view class="history-list" scroll-y>
              <view 
                class="history-item" 
                v-for="(item, index) in descriptionHistory" 
                :key="index"
                @click="useHistoryDescription(item)"
              >
                <text class="history-text">{{ item }}</text>
                <text class="history-delete" @click.stop="deleteHistoryDescription(index)">×</text>
              </view>
            </scroll-view>
          </view>
          <textarea 
            class="description-textarea" 
            v-model="form.lost_and_found_description" 
            placeholder="请输入物品描述"
            :maxlength="500"
            show-confirm-bar="false"
          />
          <view class="word-count">{{ form.lost_and_found_description.length }}/500</view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closeDescriptionPopup">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 自定义消息框组件 -->
    <message-box
      v-model="showMsgBox"
      :title="msgBoxTitle"
      :content="msgBoxContent"
      :showCancel="msgBoxShowCancel"
      :confirmText="msgBoxConfirmText"
      :cancelText="msgBoxCancelText"
      @confirm="onMsgBoxConfirm"
      @cancel="onMsgBoxCancel"
    />

    <!-- 自定义 Toast 组件 -->
    <toast
      v-model="showToast"
      :content="toastContent"
      :type="toastType"
      :duration="toastDuration"
    />

    <!-- 图片预览弹窗 -->
    <view v-if="showPreview" class="image-preview-modal" @touchmove.stop.prevent>
      <view class="preview-mask" @click="closePreview"></view>
      <view class="preview-content">
        <image
          v-if="previewImages.length > 0"
          class="preview-image"
          :src="getPreviewImgSrc(previewImages[previewIndex])"
          mode="aspectFit"
        />
        <!-- 左右切换 -->
        <view class="preview-arrow left" v-if="previewImages.length > 1 && previewIndex > 0" @click.stop="prevPreview">‹</view>
        <view class="preview-arrow right" v-if="previewImages.length > 1 && previewIndex < previewImages.length - 1" @click.stop="nextPreview">›</view>
        <!-- 指示灯 -->
        <view class="preview-indicator" v-if="previewImages.length > 1">
          <view
            v-for="(img, idx) in previewImages"
            :key="idx"
            class="indicator-dot"
            :class="{ active: idx === previewIndex }"
          ></view>
        </view>
        <!-- 关闭按钮 -->
        <view class="preview-close" @click="closePreview">×</view>
      </view>
    </view>

    <!-- 详情弹窗 -->
    <view v-if="showDetail" class="detail-modal" @touchmove.stop.prevent>
      <view class="detail-mask" @click="closeDetail"></view>
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ detailItem?.lost_and_found_name || '' }}</text>
          <view class="detail-close" @click="closeDetail">×</view>
        </view>
        <scroll-view class="detail-body" scroll-y>
          <view class="detail-images" v-if="detailItem?.images && detailItem.images.length">
            <image
              v-for="(img, idx) in detailItem.images"
              :key="idx"
              class="detail-img"
              :src="typeof img === 'object' ? (IntranetConfig.domain + img.image) : img"
              mode="aspectFill"
              @click.stop="openPreview(detailItem.images, idx)"
            />
          </view>
          <view class="detail-info">
            <view class="detail-row"><text class="label">状态：</text><text>{{ getStatusName(detailItem.lost_and_found_status) }}</text></view>
            <view class="detail-row"><text class="label">位置：</text><text>{{ detailItem.lost_and_found_location }}</text></view>
            <view class="detail-row" v-if="detailItem.lost_and_found_claimer_name"><text class="label">认领者：</text><text>{{ detailItem.lost_and_found_claimer_name }}</text></view>
            <view class="detail-row" v-if="detailItem.lost_and_found_claimer_contact"><text class="label">联系方式：</text><text>{{ detailItem.lost_and_found_claimer_contact }}</text></view>
            <view class="detail-row"><text class="label">描述：</text><text>{{ detailItem.lost_and_found_description }}</text></view>
            <view class="detail-row"><text class="label">创建时间：</text><text>{{ formatTime(detailItem.create_time) }}</text></view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { IntranetConfig, UserConfig } from '@/static/js/config'
import MessageBox from '@/components/message-box/message-box.vue'
import Toast from '@/components/toast/toast.vue'

// 获取用户信息
const userInfo = computed(() => UserConfig.getUserInfo())

// Toast 相关
const showToast = ref(false)
const toastContent = ref('')
const toastType = ref('')
const toastDuration = ref(2000)

function showCustomToast(content, type = '', duration = 2000) {
  toastContent.value = content
  toastType.value = type
  toastDuration.value = duration
  showToast.value = true
}

// 消息框相关
const showMsgBox = ref(false)
const msgBoxTitle = ref('')
const msgBoxContent = ref('')
const msgBoxShowCancel = ref(true)
const msgBoxConfirmText = ref('确定')
const msgBoxCancelText = ref('取消')
let msgBoxCallback = null

function openMsgBox({ title = '', content = '', showCancel = true, confirmText = '确定', cancelText = '取消', callback = null }) {
  msgBoxTitle.value = title
  msgBoxContent.value = content
  msgBoxShowCancel.value = showCancel
  msgBoxConfirmText.value = confirmText
  msgBoxCancelText.value = cancelText
  msgBoxCallback = callback
  showMsgBox.value = true
}

function onMsgBoxConfirm() {
  if (msgBoxCallback) msgBoxCallback(true)
}

function onMsgBoxCancel() {
  if (msgBoxCallback) msgBoxCallback(false)
}

// 列表数据
const allData = ref([]) // 全部数据
const listData = ref([]) // 当前页数据（用于分页）
const leftList = ref([])
const rightList = ref([])
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const isRefreshing = ref(false)
const searchKeyword = ref('')
const selectedFilterStatus = ref(null)
const sortType = ref('create_time_desc') // 排序类型

// 表单相关
const formPopup = ref(null)
const descriptionPopup = ref(null)
const isEdit = ref(false)
const currentId = ref(null)

// 表单数据
const form = ref({
  lost_and_found_name: '',
  lost_and_found_status: 1,
  lost_and_found_claimer_name: '',
  lost_and_found_claimer_contact: '',
  lost_and_found_location: '',
  lost_and_found_description: '',
  lost_and_found_creator: userInfo.value?.id || '',
  images: []
})

// 状态列表
const statusList = ref([
  { id: 1, name: '待认领' },
  { id: 2, name: '已认领' },
  { id: 3, name: '已失效' }
])
const selectedStatus = ref(statusList.value[0])

// 描述历史记录
const descriptionHistory = ref([])
const MAX_HISTORY_COUNT = 10

// 计算属性：本地过滤和排序
const filteredData = computed(() => {
  let data = allData.value.slice();
  // 搜索
  if (searchKeyword.value) {
    const kw = searchKeyword.value.trim().toLowerCase();
    data = data.filter(item =>
      (item.lost_and_found_name && item.lost_and_found_name.toLowerCase().includes(kw)) ||
      (item.lost_and_found_location && item.lost_and_found_location.toLowerCase().includes(kw)) ||
      (item.lost_and_found_claimer_name && item.lost_and_found_claimer_name.toLowerCase().includes(kw))
    );
  }
  // 状态筛选
  if (selectedFilterStatus.value) {
    data = data.filter(item => item.lost_and_found_status === selectedFilterStatus.value.id)
  }
  // 排序
  if (sortType.value === 'create_time_desc') {
    data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
  } else if (sortType.value === 'create_time_asc') {
    data.sort((a, b) => new Date(a.create_time) - new Date(b.create_time));
  } else if (sortType.value === 'name_asc') {
    data.sort((a, b) => (a.lost_and_found_name || '').localeCompare(b.lost_and_found_name || ''));
  } else if (sortType.value === 'name_desc') {
    data.sort((a, b) => (b.lost_and_found_name || '').localeCompare(a.lost_and_found_name || ''));
  }
  return data;
})

// 获取状态名称
function getStatusName(status) {
  const statusObj = statusList.value.find(item => item.id === status)
  return statusObj ? statusObj.name : '未知状态'
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 返回上一页
function onBack() {
  uni.navigateBack()
}

// 检查权限
function checkPermission() {
  if (!userInfo.value) {
    showCustomToast('请先登录', 'error')
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1500)
    return false
  }
  return true
}

// 图片加载完成处理
function onImageLoad(event, index, column) {
  // 可以在这里处理图片加载完成后的逻辑
  console.log('Image loaded:', event, index, column)
}

// 判断是否为已上传图片
function isUploadedImage(img) {
  if (typeof img === 'object' && img.image) {
    // 已上传图片对象
    return true;
  }
  if (typeof img === 'string') {
    return img.startsWith('http://') || img.startsWith('https://');
  }
  return false;
}

// 加载数据（只请求一次全部）
async function loadData(isRefresh = false) {
  if (isRefresh) {
    page.value = 1
    hasMore.value = true
  }
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/lostAndFound/get_lost_and_found_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      allData.value = res.data.data || []
      updateWaterfallData()
      hasMore.value = false // 全部本地分页
    } else {
      throw new Error(res.data.msg)
    }
  } catch (error) {
    showCustomToast(error.message || '加载失败', 'error')
  }
}

// 更新瀑布流数据（本地分页）
function updateWaterfallData() {
  // 本地分页
  const data = filteredData.value
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  listData.value = data.slice(0, end)
  // 瀑布流分列
  leftList.value = []
  rightList.value = []
  listData.value.forEach((item, index) => {
    if (index % 2 === 0) {
      leftList.value.push(item)
    } else {
      rightList.value.push(item)
    }
  })
  hasMore.value = end < data.length
}

// 加载更多
function loadMore() {
  if (hasMore.value) {
    page.value++
    updateWaterfallData()
  }
}

// 下拉刷新
async function onRefresh() {
  isRefreshing.value = true
  await loadData(true)
  isRefreshing.value = false
}

// 搜索
function onSearch() {
  page.value = 1
  updateWaterfallData()
}

// 状态筛选
function onStatusFilterChange(e) {
  const index = e.detail.value
  selectedFilterStatus.value = index === '' ? null : statusList.value[index]
  page.value = 1
  updateWaterfallData()
}

// 排序切换（可加排序按钮调用）
function onSortChange(type) {
  sortType.value = type
  page.value = 1
  updateWaterfallData()
}

// 添加新记录
function onAdd() {
  if (!checkPermission()) return
  isEdit.value = false
  resetForm()
  formPopup.value.open()
}

// 编辑记录
function onEdit(item) {
  if (!checkPermission()) return
  isEdit.value = true
  currentId.value = item.lost_and_found_id
  form.value = {
    lost_and_found_name: item.lost_and_found_name,
    lost_and_found_status: item.lost_and_found_status,
    lost_and_found_claimer_name: item.lost_and_found_claimer_name || '',
    lost_and_found_claimer_contact: item.lost_and_found_claimer_contact || '',
    lost_and_found_location: item.lost_and_found_location,
    lost_and_found_description: item.lost_and_found_description || '',
    lost_and_found_creator: userInfo.value?.id || '',
    images: Array.isArray(item.images) ? item.images.slice() : []
  }
  selectedStatus.value = statusList.value.find(s => s.id === item.lost_and_found_status) || statusList.value[0]
  formPopup.value.open()
}

// 重置表单
function resetForm() {
  form.value = {
    lost_and_found_name: '',
    lost_and_found_status: 1,
    lost_and_found_claimer_name: '',
    lost_and_found_claimer_contact: '',
    lost_and_found_location: '',
    lost_and_found_description: '',
    lost_and_found_creator: userInfo.value?.id || '',
    images: []
  }
  selectedStatus.value = statusList.value[0]
  currentId.value = null
}

// 关闭表单弹窗
function closeFormPopup() {
  formPopup.value.close()
}

// 图片相关
function onAddImg() {
  uni.chooseImage({
    count: 9 - form.value.images.length,
    success: (res) => {
      form.value.images = [...form.value.images, ...res.tempFilePaths]
    }
  })
}

function onImgDelete(index) {
  const img = form.value.images[index];
  // 判断是否为已上传图片（有图片 id）
  if (img && typeof img === 'object' && img.id) {
    uni.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const delRes = await uni.request({
              url: IntranetConfig.domain + `api/lostAndFound/delete_lost_and_found_image/${img.id}/`,
              method: 'DELETE',
              header: IntranetConfig.headers
            });
            if (delRes.data.code === 200) {
              showCustomToast('图片已删除', 'success');
              form.value.images.splice(index, 1);
            } else {
              showCustomToast(delRes.data.msg || '删除失败', 'error');
            }
          } catch (e) {
            showCustomToast('删除失败', 'error');
          }
        }
      }
    });
  } else {
    // 本地图片直接移除
    form.value.images.splice(index, 1);
  }
}

// 状态选择事件
function onStatusChange(e) {
  const index = e.detail.value
  selectedStatus.value = statusList.value[index]
  form.value.lost_and_found_status = selectedStatus.value.id
}

// 描述弹窗
function showDescriptionPopup() {
  descriptionPopup.value.open()
}

function closeDescriptionPopup() {
  // 如果描述不为空且不在历史记录中，则添加到历史记录
  if (form.value.lost_and_found_description && !descriptionHistory.value.includes(form.value.lost_and_found_description)) {
    descriptionHistory.value.unshift(form.value.lost_and_found_description)
    // 保持历史记录数量不超过最大值
    if (descriptionHistory.value.length > MAX_HISTORY_COUNT) {
      descriptionHistory.value.pop()
    }
    saveDescriptionHistory()
  }
  descriptionPopup.value.close()
}

// 使用历史描述
function useHistoryDescription(description) {
  form.value.lost_and_found_description = description
}

// 删除历史描述
function deleteHistoryDescription(index) {
  descriptionHistory.value.splice(index, 1)
  saveDescriptionHistory()
}

// 保存历史记录到本地存储
function saveDescriptionHistory() {
  uni.setStorageSync('lostAndFoundDescriptionHistory', JSON.stringify(descriptionHistory.value))
}

// 保存函数
async function onSave() {
  // 检查权限
  if (!checkPermission()) return

  // 表单验证
  if (!form.value.lost_and_found_name) {
    showCustomToast('请输入物品名称', 'error')
    return
  }
  if (!form.value.lost_and_found_location) {
    showCustomToast('请输入物品位置', 'error')
    return
  }

  // 状态为已认领时，校验认领者信息
  if (form.value.lost_and_found_status === 2) {
    if (!form.value.lost_and_found_claimer_name) {
      showCustomToast('请输入认领者姓名', 'error')
      return
    }
    if (!form.value.lost_and_found_claimer_contact) {
      showCustomToast('请输入认领者联系方式', 'error')
      return
    }
  }

  uni.showLoading({
    title: '保存中...',
    mask: true
  })

  try {
    let res
    if (isEdit.value) {
      res = await uni.request({
        url: IntranetConfig.domain + `api/lostAndFound/update_lost_and_found/${currentId.value}/`,
        method: 'POST',
        header: IntranetConfig.headers,
        data: form.value
      })
    } else {
      res = await uni.request({
      url: IntranetConfig.domain + 'api/lostAndFound/create_lost_and_found/',
      method: 'POST',
      header: IntranetConfig.headers,
      data: form.value
    })
    }

    if (res.data.code === 200) {
      const lostId = isEdit.value ? currentId.value : res.data.data.lost_and_found_id;

      // 只要不是已上传的图片都要上传
      const needUploadImages = form.value.images.filter(img => !isUploadedImage(img));
      if (needUploadImages.length > 0) {
        await Promise.all(needUploadImages.map(imagePath => {
          return new Promise((resolve, reject) => {
            uni.uploadFile({
              url: IntranetConfig.domain + `api/lostAndFound/upload_lost_and_found_image/${lostId}/`,
              filePath: imagePath,
              fileType: 'image',
              name: 'image',
              success: (res) => {
                try {
                  const data = JSON.parse(res.data)
                  if (data.code === 200) resolve(data)
                  else reject(new Error(data.msg))
                } catch (e) {
                  reject(new Error('解析响应数据失败'))
                }
              },
              fail: (err) => reject(new Error(err.errMsg || '上传失败'))
            })
            })
        }))
      }

      showCustomToast(isEdit.value ? '更新成功' : '添加成功', 'success')
      closeFormPopup()
      loadData(true)
    } else {
      throw new Error(res.data.msg)
    }
        } catch (error) {
    showCustomToast(error.message || (isEdit.value ? '更新失败' : '添加失败'), 'error')
  } finally {
    uni.hideLoading()
  }
}

// 删除记录
function onDelete(item) {
  if (!checkPermission()) return
  openMsgBox({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    callback: async (confirmed) => {
      if (confirmed) {
        try {
          const res = await uni.request({
            url: IntranetConfig.domain + `api/lostAndFound/delete_lost_and_found/${item.lost_and_found_id}/`,
            method: 'DELETE',
            header: IntranetConfig.headers
          })

          if (res.data.code === 200) {
            showCustomToast('删除成功', 'success')
            loadData(true)
    } else {
            throw new Error(res.data.msg)
    }
  } catch (error) {
          console.error('删除错误：', error)
          showCustomToast(error.message || '删除失败', 'error')
        }
      }
    }
  })
}

// 点击记录
function onItemClick(item) {
  detailItem.value = item
  showDetail.value = true
}

function closeDetail() {
  showDetail.value = false
}

// 页面加载
onMounted(() => {
  if (checkPermission()) {
    loadData()
    // 从本地存储加载历史记录
    const history = uni.getStorageSync('lostAndFoundDescriptionHistory')
    if (history) {
      descriptionHistory.value = JSON.parse(history)
    }
  }
})

// 图片预览相关
const showPreview = ref(false)
const previewIndex = ref(0)
const previewImages = ref([])

function getPreviewImgSrc(img) {
  if (typeof img === 'object' && img.image) {
    return IntranetConfig.domain + img.image
  }
  return img
}

function openPreview(images, index) {
  if (!Array.isArray(images) || images.length === 0) return;
  previewImages.value = images;
  previewIndex.value = (typeof index === 'number' && index >= 0 && index < images.length) ? index : 0;
  showPreview.value = true;
}

function closePreview() {
  showPreview.value = false
}

function prevPreview() {
  if (previewIndex.value > 0) previewIndex.value--
}

function nextPreview() {
  if (previewIndex.value < previewImages.value.length - 1) previewIndex.value++
}

// 详情弹窗相关
const showDetail = ref(false)
const detailItem = ref(null)
</script>

<style scoped lang="scss">
.lost-and-found-page {
  background: #f8f9fa;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 96rpx;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  
  .nav-back { 
    color: #333; 
    font-size: 44rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
  
  .nav-title { 
    flex: 1; 
    text-align: center; 
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .nav-add {
    color: #ff7e2d;
    font-size: 44rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
    
    &:active {
      background: rgba(255, 126, 45, 0.1);
    }
  }
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  background: #fff;
  margin-bottom: 24rpx;

  .search-input-wrap {
    flex: 1;
  display: flex;
  align-items: center;
    background: #f5f5f5;
    border-radius: 32rpx;
    padding: 0 24rpx;
    margin-right: 24rpx;
    
    .search-icon {
      font-size: 32rpx;
      color: #999;
      margin-right: 16rpx;
}

    .search-input {
      flex: 1;
      height: 64rpx;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  .status-picker {
  width: 160rpx;
    height: 64rpx;
    background: #f5f5f5;
    border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
    
    .picker-value {
      font-size: 28rpx;
      color: #333;
  
      &:empty::before {
        content: '全部状态';
        color: #999;
      }
    }
  }
  }
  
.list-container {
  height: calc(100vh - 184rpx);
  background: #f8f9fa;
}

.waterfall-container {
  display: flex;
  padding: 24rpx;
  gap: 24rpx;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.list-item {
  background: #fff;
    border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  
  .item-images {
    width: 100%;
    
    .item-image {
      width: 100%;
      height: auto;
      display: block;
    }
  }
  
  .item-content {
    padding: 24rpx;
    
    .item-header {
    display: flex;
    align-items: center;
      justify-content: space-between;
      margin-bottom: 16rpx;
      
      .item-name {
    font-size: 32rpx;
        font-weight: 600;
        color: #333;
        flex: 1;
        margin-right: 16rpx;
}

      .item-status {
        font-size: 24rpx;
        padding: 4rpx 16rpx;
        border-radius: 24rpx;
        flex-shrink: 0;
        
        &.status-1 {
          background: #e6f7ff;
          color: #1890ff;
        }
        
        &.status-2 {
          background: #f6ffed;
          color: #52c41a;
        }
        
        &.status-3 {
          background: #f5f5f5;
          color: #999;
        }
      }
    }
    
    .item-info {
  display: flex;
  align-items: center;
      margin-bottom: 16rpx;
      
      .item-location {
        font-size: 28rpx;
        color: #666;
        margin-right: 24rpx;
      }
      
      .item-time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .item-description {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      margin-bottom: 16rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .item-creator {
      display: flex;
      align-items: center;
      margin-top: 16rpx;
      
      .creator-avatar {
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
        margin-right: 12rpx;
      }
      
      .creator-name {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
  
  .item-actions {
    display: flex;
    justify-content: flex-end;
    padding: 16rpx 24rpx;
    border-top: 1rpx solid #f5f5f5;
    
    .action-btn {
      font-size: 28rpx;
      padding: 8rpx 24rpx;
      border-radius: 24rpx;
      margin-left: 16rpx;
  transition: all 0.3s;
      
      &.edit {
        background: #e6f7ff;
        color: #1890ff;
  
  &:active {
          background: darken(#e6f7ff, 5%);
        }
      }
      
      &.delete {
        background: #fff1f0;
        color: #ff4d4f;
        
        &:active {
          background: darken(#fff1f0, 5%);
        }
      }
    }
  }
  }
  
.loading-more, .no-more {
  text-align: center;
  padding: 24rpx 0;
  
  .loading-text, .no-more-text {
    font-size: 24rpx;
    color: #999;
  }
}

.footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  
  .add-btn {
    width: 100%;
    height: 88rpx;
    background: #ff7e2d;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
      background: darken(#ff7e2d, 5%);
    }
  }
}

.form-popup {
  width: 90vw;
  max-width: 600rpx;
  max-height: 90vh;
  background: #fff;
  border-radius: 32rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding-left: 32rpx;
  padding-right: 32rpx;
  box-shadow: 0 12rpx 48rpx rgba(0,0,0,0.12), 0 2rpx 8rpx rgba(0,0,0,0.04);
  border: 1rpx solid #f0f0f0;
  animation: popup-fade-in 0.25s cubic-bezier(.4,0,.2,1);
}

@keyframes popup-fade-in {
  0% { transform: scale(0.95); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}

.popup-header {
    display: flex;
    align-items: center;
  justify-content: center;
  padding: 32rpx 0 16rpx 0;
  border-bottom: 1rpx solid #f2f2f2;
  background: #fff;
  position: relative;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #222;
  letter-spacing: 1rpx;
  text-align: center;
  flex: 1;
}

.popup-close {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 44rpx;
  color: #bbb;
  padding: 12rpx;
  border-radius: 50%;
  transition: background 0.2s;
  cursor: pointer;
    &:active {
    background: #f5f5f5;
    }
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 8rpx 0 8rpx;
  background: #fff;
    }
    
.form-section {
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  margin-top: 24rpx;
  padding-left: 0;
  padding-right: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx 32rpx;
  padding: 0 0 0 0;
  margin-bottom: 12rpx;
    }
    
.form-group {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
      min-width: 0;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  font-weight: 600;
  margin-bottom: 4rpx;
  &.required:after {
    content: '*';
    color: #ff7e2d;
    margin-left: 4rpx;
  }
}

.form-input, .form-picker {
  width: 100%;
  box-sizing: border-box;
  height: 80rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
      color: #333;
  border: 2rpx solid transparent;
  transition: border-color 0.2s, background 0.2s;
  &:focus {
    border-color: #ff7e2d;
    background: #fff;
  }
      &::placeholder {
    color: #bbb;
      }
    }
    
.form-picker {
  display: flex;
  align-items: center;
      .picker-value {
    font-size: 28rpx;
        color: #333;
        &:empty::before {
          content: '请选择';
          color: #999;
        }
      }
    }
    
.lost-img-list-horizontal {
  width: 100%;
  overflow-x: auto;
  margin-bottom: 24rpx;
  box-sizing: border-box;
  padding-left: 0;
  padding-right: 0;
}

.img-list-row {
      display: flex;
  flex-direction: row;
      align-items: center;
  padding: 8rpx 0;
  box-sizing: border-box;
  gap: 24rpx;
}

.img-box-horizontal {
  position: relative;
  width: 180rpx;
  height: 180rpx;
  margin-right: 0;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: box-shadow 0.2s, transform 0.2s;
  border: 2rpx solid #f5f5f5;
  &:active {
    transform: scale(0.97);
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08);
  }
  .lost-img-horizontal {
    width: 180rpx;
    height: 180rpx;
    border-radius: 20rpx;
    object-fit: cover;
  }
  .img-delete-horizontal {
    position: absolute;
    top: -12rpx;
    right: -12rpx;
    width: 44rpx;
    height: 44rpx;
    background: #ff7e2d;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;
    box-shadow: 0 4rpx 12rpx rgba(255, 126, 45, 0.3);
    z-index: 2;
    transition: all 0.3s;
    cursor: pointer;
    &:active {
      transform: scale(0.9);
      background: darken(#ff7e2d, 5%);
    }
    }
  }
  
.add-img-horizontal {
  border: 2rpx dashed #ff7e2d;
  background: #fff6ed;
  transition: background 0.2s, border-color 0.2s;
  &:hover {
    background: #ffe3cc;
    border-color: #ffae7b;
  }
  .add-icon-horizontal {
    font-size: 64rpx;
    color: #ff7e2d;
    font-weight: bold;
  }
}

.description-group {
  padding: 0 0 0 0;
  margin-top: 8rpx;
}

.description-preview {
  height: 80rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 2rpx solid transparent;
  transition: border-color 0.2s, background 0.2s;
  cursor: pointer;
  &:active, &:focus {
    border-color: #ff7e2d;
    background: #fff;
  }
  .description-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    &:empty::before {
      content: '请输入物品描述';
      color: #999;
    }
  }
  .arrow {
    color: #bbb;
    font-size: 28rpx;
    margin-left: 16rpx;
  }
}

.popup-footer {
  display: flex;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f5f5f5;
  background: #fff;
  gap: 24rpx;
  .cancel-btn, .confirm-btn {
    flex: 1;
    height: 88rpx;
    border: none;
    border-radius: 18rpx;
    font-size: 32rpx;
    font-weight: 600;
    transition: all 0.2s;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
    &:active {
      transform: scale(0.97);
    }
  }
  .cancel-btn {
    background: #f5f5f5;
    color: #666;
    &:active {
      background: #ececec;
    }
  }
  .confirm-btn {
    background: linear-gradient(90deg, #ff9a44 0%, #ff7e2d 100%);
    color: #fff;
    &:active {
      background: #ff7e2d;
    }
  }
}

.description-popup {
  width: 86vw;
  max-width: 540rpx;
  background: #fff;
  border-radius: 28rpx;
  box-shadow: 0 12rpx 48rpx rgba(0,0,0,0.13), 0 2rpx 8rpx rgba(0,0,0,0.04);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: popup-fade-in 0.25s cubic-bezier(.4,0,.2,1);
}
  
.description-popup .popup-header {
    display: flex;
    align-items: center;
  justify-content: center;
  padding: 28rpx 0 12rpx 0;
  border-bottom: 1rpx solid #f2f2f2;
    background: #fff;
  position: relative;
}

.description-popup .popup-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #222;
  text-align: center;
  flex: 1;
    }
    
.description-popup .popup-close {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
      font-size: 40rpx;
  color: #bbb;
  padding: 10rpx;
      border-radius: 50%;
  transition: background 0.2s;
  cursor: pointer;
      &:active {
        background: #f5f5f5;
    }
  }
  
.description-popup .popup-content {
  padding: 24rpx 32rpx 0 32rpx;
    background: #fff;
  flex: 1;
  min-height: 260rpx;
  max-height: 420rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.history-section {
  margin-bottom: 18rpx;
}

.history-title {
  font-size: 26rpx;
  color: #888;
  margin-bottom: 8rpx;
  font-weight: 600;
}

.history-list {
  max-height: 120rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.history-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 14rpx;
  padding: 12rpx 20rpx;
  font-size: 26rpx;
  color: #333;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
  &:hover, &:active {
    background: #ffe3cc;
  }
  .history-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .history-delete {
    margin-left: 16rpx;
    color: #ff7e2d;
    font-size: 30rpx;
    font-weight: bold;
    border-radius: 50%;
    padding: 0 8rpx;
    transition: background 0.2s;
    &:active {
      background: #ffe3cc;
    }
  }
}
    
    .description-textarea {
      width: 100%;
  min-height: 120rpx;
  max-height: 200rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
  border: 2rpx solid transparent;
  font-size: 28rpx;
  color: #333;
  padding: 18rpx 24rpx;
  margin-top: 8rpx;
  margin-bottom: 8rpx;
      box-sizing: border-box;
  transition: border-color 0.2s, background 0.2s;
  resize: none;
  &:focus {
    border-color: #ff7e2d;
    background: #fff;
      }
    }
    
    .word-count {
      text-align: right;
      font-size: 24rpx;
  color: #bbb;
  margin-bottom: 8rpx;
  }
  
.description-popup .popup-footer {
  display: flex;
  padding: 20rpx 32rpx 24rpx 32rpx;
    border-top: 1rpx solid #f5f5f5;
    background: #fff;
  gap: 24rpx;
    .confirm-btn {
    flex: 1;
    height: 80rpx;
      border: none;
    border-radius: 16rpx;
    font-size: 30rpx;
    font-weight: 600;
    background: linear-gradient(90deg, #ff9a44 0%, #ff7e2d 100%);
    color: #fff;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
    transition: all 0.2s;
      &:active {
      background: #ff7e2d;
      transform: scale(0.97);
    }
  }
}

.image-preview-modal {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.preview-mask {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.85);
}
.preview-content {
  position: relative;
  z-index: 2;
  width: 90vw;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.preview-image {
  max-width: 90vw;
  max-height: 60vh;
  border-radius: 12rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.25);
  background: #fff;
}
.preview-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  font-size: 60rpx;
  color: #fff;
  background: rgba(0,0,0,0.25);
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3;
  cursor: pointer;
  user-select: none;
  &.left { left: 12vw; }
  &.right { right: 12vw; }
}
.preview-indicator {
  position: absolute;
  bottom: 32rpx;
  left: 0; right: 0;
  display: flex;
  justify-content: center;
  gap: 16rpx;
  z-index: 4;
}
.indicator-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background: #fff;
  opacity: 0.5;
  transition: opacity 0.2s, background 0.2s;
  &.active {
    opacity: 1;
    background: #ff7e2d;
  }
}
.preview-close {
  position: absolute;
  top: 24rpx;
  right: 24rpx;
  font-size: 48rpx;
    color: #fff;
  background: rgba(0,0,0,0.25);
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 5;
  cursor: pointer;
  user-select: none;
}

.detail-modal {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  z-index: 9998;
  display: flex;
  align-items: center;
  justify-content: center;
}
.detail-mask {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5);
}
.detail-content {
  position: relative;
  z-index: 2;
  width: 86vw;
  max-width: 600rpx;
  max-height: 80vh;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.18);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 32rpx 16rpx 32rpx;
  border-bottom: 1rpx solid #f2f2f2;
  background: #fff;
}
.detail-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #222;
}
.detail-close {
  font-size: 44rpx;
  color: #bbb;
  padding: 10rpx;
  border-radius: 50%;
  transition: background 0.2s;
  cursor: pointer;
  &:active { background: #f5f5f5; }
}
.detail-body {
  flex: 1;
  padding: 24rpx 32rpx;
  overflow-y: auto;
}
.detail-images {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 18rpx;
}
.detail-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  object-fit: cover;
  background: #f8f9fa;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}
.detail-info {
  display: flex;
  flex-direction: column;
  gap: 14rpx;
}
.detail-row {
  font-size: 28rpx;
  color: #333;
  display: flex;
  align-items: flex-start;
  .label {
    color: #888;
    min-width: 90rpx;
    font-weight: 500;
  }
}
</style>    
